<?php

namespace Frieza\Modules\Position\Controllers;

use Biz\service\advertisement\apiModule\BaseModule;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\position\PositionConstInterface;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Exception;
use Illuminate\Http\Request;

trait BaseTrait
{

    public function gifControl(Form $form, $column = 'base.play_times', $label = '播放次数', $help = '仅上传gif时需要选择，静态图忽略此选项')
    {
        $form->select($column, $label)->options(BaseModule::GIF_PLAY_TIMES)->help($help);
    }

    public function labelColor($count = 5): array
    {
        $pool = [
            'success','warning','danger', 'info','default',];
        $color = [];
        for ($i = 0; $i < $count; $i ++) {
            $color[] = $pool[$i % 5];
        }
        return $color;
    }

    public function relationCheck($account, $relation)
    {
        //查询占位信息
        if (empty($relation)) throw new Exception('占位信息不存在');
        $project_id = $relation['project_id'] ?? 0;
        $ad_id = $relation['ad_id'] ?? 0;
        //查询用户puck账号id
        $adminId = \Doraemon\model\Position\Admin::get('id', ['account' => $account]);
        //查询占位项目权限
        $project = empty($adminId) ? [] : \Doraemon\model\Position\PositionProject::get('*', ['project_status' => \Doraemon\model\Position\PositionProject::PROJECT_STATUS_OK, 'admin_id' => $adminId, 'id' => $project_id]);
//        if (empty($project)) throw new Exception('项目权限不足');
        //查询项目中的配置区间
        $config = \Doraemon\model\Position\PositionAdType::get('position_config', ['id' => $ad_id]);
        if (empty($config)) throw new Exception('占位配置不存在');
        $config = json_decode($config, true);
        $config_module_type = $config['module_type'] ?? PositionRules::MODULE_TYPE_POSITION;
        $config_position_id = $config['position_id'] ?? 0;
        $this->base_field_pos = $config['pos'] ?? 0;
        if ($config_module_type != PositionRules::MODULE_TYPE_POSITION) throw new Exception('占位配置不存在');
        if ($config_position_id != $this->positionId) throw new Exception('占位资源位类型不正确');
    }

    public function imgHelp($pos = null, $separator = ' ; '): string
    {
        $help = [];
        $rules = self::posRulesMap($this->positionId);
        foreach ($rules as $key => $rows) {
            switch ($key) {
                case 'img_size':
                    $help[] = '图片大小规格 : ' . htmlentities($rows['operator']) . ' ' . self::conversion($rows['value']);
                    break;
                case 'img_area':
                    $allow = [];
                    foreach ($rows as $k => $row) {
                        if (is_null($pos)) $allow[] = isset($row['h']) ? "[{$row['w']} x {$row['h']}]" : "宽度限制{$row['w']}";
                        if (is_numeric($pos) && ($k == $pos)) {
                            $allow[] = "[{$row['w']} x {$row['h']}]";
                            if (!empty($row['desc'])) $allow[] = $row['desc'];
                        }
                    }
                    $help[] = empty($allow) ? '' : "图片宽高规格 : " . implode($separator, $allow);

                    break;
            }
        }

        return implode($separator, $help);
    }

    public function bannerFormWithCheck(Form $form, $column = 'base.pic_id', $label = 'banner图')
    {
        $form->bh('rules.img_w');
        $form->bh('rules.img_h');
        $form->bh('rules.img_size');
        $form->imgUpload($column, $label)
            ->help($this->imgHelp())
            ->setImgSizeInputId("rules.img_size")
            ->setImgWidthInputId("rules.img_w")
            ->setImgHeightInputId("rules.img_h");
        $form->radio('rules.check', $label . '校验')->options(['否', '是'])->default(1);
    }

    public function bannerForm2SearchResultCard(Form $form, $column = 'base.pic_id', $default_pos = null)
    {
        $rules = self::posRulesMap($this->positionId);
        $columnArr = [
            'base.pic_id',
            'base.single_pic_id'
        ];
        $img_area = $rules['img_area'] ?? [];
        foreach ($img_area as $pos => $v) {
            if (!is_null($default_pos) && ($default_pos != $pos)) continue;
            $posColumn = $columnArr[$pos];
            $label = $v['label'];
            $wColumn = 'rules.img_w.' . $pos;
            $hColumn = 'rules.img_h.' . $pos;
            $sizeColumn = 'rules.img_size.' . $pos;
            $form->bh($wColumn);
            $form->bh($hColumn);
            $form->bh($sizeColumn);
            $form->imgUpload($posColumn, $label)
                ->help($this->imgHelp($pos))
                ->setImgSizeInputId($sizeColumn)
                ->setImgWidthInputId($wColumn)
                ->setImgHeightInputId($hColumn)
            ;
            $form->radio('rules.check.' . $pos, $label . '校验')->options(['否', '是'])->default(1);
        }
    }

    public function bannerForm2AppStart(Form $form, $column = 'base.pic_id', $default_pos = null)
    {
        $rules = self::posRulesMap($this->positionId);
        $img_area = $rules['img_area'] ?? [];
        foreach ($img_area as $pos => $v) {
            if (!is_null($default_pos) && ($default_pos != $pos)) continue;
            $posColumn = $column . '.' . $pos;
            $label = $v['label'];
            $wColumn = 'rules.img_w.' . $pos;
            $hColumn = 'rules.img_h.' . $pos;
            $sizeColumn = 'rules.img_size.' . $pos;
            $w = $v['w'];
            $h = $v['h'];
            $form->bh($wColumn);
            $form->bh($hColumn);
            $form->bh($sizeColumn);
            $form->imgUpload($posColumn, $label)
                ->help($this->imgHelp($pos))
                ->setImgSizeInputId($sizeColumn)
                ->setImgWidthInputId($wColumn)
                ->setImgHeightInputId($hColumn)
//                ->setMaxImageWight($w)->setMinImageWight($w)
//                ->setMaxImageHeight($h)->setMinImageHeight($h)
                ;
        }
    }

    public function rulesValid($inputRules, $pos = null)
    {
        $check = $inputRules['check'] ?? 0;

        if (!$check) return;

        $rules = self::posRulesMap($this->positionId);

        foreach ($rules as $key => $rows) {
            switch ($key) {
                case 'img_size':
                    $title = '当前图片';
                    foreach ($rows as $k => $row) {
                        if (!is_null($pos) && ($k != $pos)) continue;
                        $title = empty($row['label']) ? '当前图片' : $row['label'];
                    }
                    $input = $inputRules['img_size'] ?? 0;
                    $bool = version_compare($input, $rows['value'], $rows['operator']);
                    if (!$bool) throw new \Exception($title . '大小需要 ' . htmlentities($rows['operator']) . ' ' . self::conversion($rows['value']) . ' 当前图片大小 ' . self::conversion($input));
                    break;
                case 'img_area':
                    $input_w = $inputRules['img_w'] ?? '0';
                    $input_h = $inputRules['img_h'] ?? '0';
                    $allow = [];
                    $throw = true;
                    $title = '当前图片';
                    foreach ($rows as $k => $row) {
                        if (!is_null($pos) && ($k != $pos)) continue;
                        $title = empty($row['label']) ? '当前图片' : $row['label'];
                        $allow[] = isset($row['h']) ? "[{$row['w']} x {$row['h']}]" : "宽度限制{$row['w']}";
                        if ($input_w == $row['w']) $throw = false;
                        if (isset($row['h']) && ($input_h != $row['h'])) $throw = true;
                        if (!$throw) break;
                    }

                    if ($throw) throw new \Exception($title . "宽高[$input_w x $input_h],图片宽高允许: " . implode(' ', $allow));
                    break;
            }
        }
    }

    /**
     * 生成路由
     * @param       $sign
     * @param null  $default
     * @param array $params
     * @return mixed|string
     */
    public function generateRoute($sign, $default = null, $params = []): string
    {
        $tempRoute = $this->getRoute();

        $newRouteBool = strstr($tempRoute, '.') == false;

        if ($newRouteBool) {
            $tempRoute = $tempRoute . '.' . $sign;
            return route($tempRoute, empty($params) ? $this->getRouteParams() : $params);
        }

        return $default ? $default : route($tempRoute, empty($params) ? $this->getRouteParams() : $params);
    }

    public static function conversion($size): string
    {
        $unit = ['B','KB','MB','GB','TB','PB'];
        //指数
        $i = $size < 1024 ? 0 : floor(log($size,1024));
        //基数
        $operand = pow(1024, $i);

        return round($size / $operand,2) . $unit[$i];
    }

    public function getRoute(): string
    {
        $route = explode('\\', __CLASS__);
        $controller = end($route);
        $class = str_replace(["Controller"], '', $controller);
        return lcfirst($class);
    }

    public function extendSaveBaseInfo(Request $request): array
    {
        return [];
    }

    /**
     * 资源位校验规则
     */
    public static function posRulesMap($id)
    {
        $rules = [
            PositionConstInterface::SEARCH_RESULT_CARD => [//搜索结果
                'img_size' => ['operator' => '<=', 'value' => '102400'],
                'img_area' => [
                    ['label' => '双列图片', 'w' => 500, 'h' => 625],
                    ['label' => '单列图片', 'w' => 750, 'h' => 170],
                ],
            ],
            PositionConstInterface::APP_START => [//启动屏
                'img_size' => ['operator' => '<=', 'value' => '819200'],
                'img_area' => [
                    ['label' => '完美通用(必传)', 'desc' => '完美通用','w' => 1242, 'h' => 2700],
                    ['label' => 'iOS 全面屏', 'desc' => 'iOS 全面屏 (0.1 ~ 0.49)', 'w' => 1126, 'h' => 2436],
                    ['label' => 'iOS 普通屏', 'desc' => 'iOS 普通屏 (0.56 ~ 1)', 'w' => 1242, 'h' => 2208],
                    ['label' => 'Android 全面屏', 'desc' => 'Android 全面屏 (0.5 ~ 0.55)','w' => 1080, 'h' => 2160],
                    ['label' => 'Android 普通屏', 'desc' => 'Android 普通屏 (0.56 ~ 1)', 'w' => 1080, 'h' => 1920],
                ],
            ],
            PositionConstInterface::HOME_ROOF => [ //二楼
                'img_size' => ['operator' => '<', 'value' => '512000'],
                'img_area' => [
                    ['w' => 1000, 'h' => 1000],
                ],
            ],
            PositionConstInterface::HOME_TODAY_ARTICLE => [ //今日整屋
                'img_size' => ['operator' => '<', 'value' => '102400'],
                'img_area' => [
                    ['w' => 500, 'h' => 311],
                ],
            ],
            PositionConstInterface::HOME_CAROUSEL_V5 => [//首页三拼轮播banner
                'img_size' => ['operator' => '<', 'value' => '102400'],
                'img_area' => [
                    ['w' => 500, 'h' => 625],
                ],
            ],
            PositionConstInterface::DIARY_SQUARE_CAROUSEL_BANNER => [//日记广场轮播图
                'img_size' => ['operator' => '<', 'value' => '102400'],
                'img_area' => [
                    ['w' => 750, 'h' => 170],
                ],
            ],
            PositionConstInterface::TAB_POPUPS => [//弹屏
                'img_size' => ['operator' => '<', 'value' => '409600'],
                'img_area' => [
                    ['w' => 750, 'h' => 925],
                ],
            ],
            PositionConstInterface::CONTRACTOR_CAROUSEL_BANNER => [ //装修公司banner
                'img_size' => ['operator' => '<', 'value' => '512000'],
                'img_area' => [
                    ['w' => 750, 'h' => 170],
                ],
            ],
            PositionConstInterface::USER_DETAIL_CAROUSEL_BANNER => [//创作中心banner
                'img_size' => ['operator' => '<', 'value' => '204800'],
                'img_area' => [
                    ['w' => 750, 'h' => 170],
                ],
            ],
            PositionConstInterface::HOME_RECOMMEND_GREET_BANNER => [//推荐-顶部横 banner
                'img_size' => ['operator' => '<', 'value' => '204800'],
                'img_area' => [
                    ['w' => 750, 'h' => 170],
                ],
            ],
            PositionConstInterface::PHOTO_INDEX_CARD => [//推荐-顶部横 banner
                'img_size' => ['operator' => '<', 'value' => '409600'],
                'img_area' => [
                    ['w' => 500, 'h' => 625],
                ],
            ],
            PositionConstInterface::HOME_RECOMMEND_CARD => [//推荐-第 5,10,15,20,25 个卡片
                'img_size' => ['operator' => '<', 'value' => '409600'],
                'img_area' => [
                    ['w' => 500],
                ],
            ],
            115 => [//推荐-顶部横 banner
                'img_size' => ['operator' => '<', 'value' => '204800'],
                'img_area' => [
                    ['w' => 750, 'h' => 170],
                ],
            ],
        ];

        return $rules[$id] ?? [];
    }

    public function beforeTab(Tab $tab)
    {
    }

    public function afterTab(Tab $tab, Request $request)
    {
    }

    public function init()
    {
    }

    public function extendGrid($list)
    {
        return $list;
    }

    public function beforeTitleForm(Form $form)
    {
    }

    public function beforeLinkForm(Form $form)
    {
    }

    public function beforeSortForm(Form $form)
    {
    }

    public function beforeShareForm(Form $form)
    {
    }

    public function beforeDisplayForm(Form $form)
    {
    }

    public function beforeReasonForm(Form $form)
    {
    }

    public function beforeProfileForm(Form $form)
    {
    }

    public function saveModule(Request $request, $baseInfoId)
    {
    }

    public function delModule($id)
    {
    }


}
